package com.weijian.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.weijian.dal.entity.Order;
import com.weijian.dal.enums.OrderStatus;
import com.weijian.dal.mapper.OrderMapper;
import com.weijian.service.OrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单过期监听器
 * 定时扫描过期订单并自动取消
 *
 * @author weijian
 */
@Slf4j
@Component
public class OrderExpireListener {

    @Resource
    private OrderService orderService;

    @Resource
    private OrderMapper orderMapper;

    /**
     * 每30秒检查一次过期订单
     * 自动取消过期订单并恢复库存
     */
    @Scheduled(fixedDelay = 30000)
    public void checkExpiredOrders() {
        log.debug("开始检查过期订单...");
        try {
            // 查询已过期的待支付订单
            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Order::getStatus, OrderStatus.PENDING)
                    .lt(Order::getExpireTime, LocalDateTime.now())
                    .eq(Order::getDeleted, 0);

            List<Order> expiredOrders = orderMapper.selectList(queryWrapper);
            if (expiredOrders.isEmpty()) {
                log.debug("暂无过期订单");
                return;
            }
            log.info("发现{}个过期订单，开始处理...", expiredOrders.size());
            for (Order order : expiredOrders) {
                try {
                    // 自动取消过期订单
                    cancelExpiredOrder(order);
                } catch (Exception e) {
                    log.error("取消过期订单失败 - 订单ID: {}, 错误: {}", order.getId(), e.getMessage(), e);
                }
            }
            log.info("过期订单处理完成");
        } catch (Exception e) {
            log.error("检查过期订单时发生错误", e);
        }
    }

    /**
     * 取消过期订单
     *
     * @param order 过期订单
     */
    private void cancelExpiredOrder(Order order) {
        Long orderId = order.getId();
        Long userId = order.getUserId();
        log.info("自动取消过期订单 - 订单ID: {}, 订单号: {}", orderId, order.getOrderNo());
        // 调用订单服务取消订单
        orderService.cancelOrder(orderId, userId);
        log.info("过期订单已自动取消 - 订单ID: {}, 用户ID: {}", orderId, userId);
    }
}